package cn.yuanqiao.framework.web.service;

import cn.yuanqiao.auth.service.SysRecordLogService;
import cn.yuanqiao.common.config.YuanQiaoConfig;
import cn.yuanqiao.common.constant.CacheConstants;
import cn.yuanqiao.common.constant.Constants;
import cn.yuanqiao.common.constant.UserConstants;
import cn.yuanqiao.common.core.domain.entity.SysUser;
import cn.yuanqiao.common.core.domain.model.LoginUser;
import cn.yuanqiao.common.core.redis.RedisCache;
import cn.yuanqiao.common.core.text.Convert;
import cn.yuanqiao.common.exception.ServiceException;
import cn.yuanqiao.common.exception.user.*;
import cn.yuanqiao.common.service.SysPermissionService;
import cn.yuanqiao.common.utils.DateUtils;
import cn.yuanqiao.common.utils.MessageUtils;
import cn.yuanqiao.common.utils.StringUtils;
import cn.yuanqiao.common.utils.ip.IpUtils;
import cn.yuanqiao.framework.manager.AsyncManager;
import cn.yuanqiao.framework.manager.factory.AsyncFactory;
import cn.yuanqiao.framework.security.context.AuthenticationContextHolder;
import cn.yuanqiao.system.service.ISysConfigService;
import cn.yuanqiao.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;
import java.util.Set;

/**
 * 登录校验方法
 *
 * @author ruoyi
 */
@Component
public class SysLoginService
{
    @Autowired
    private TokenService tokenService;

    @Resource
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private SysPasswordService sysPasswordService;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private SysRecordLogService sysRecordLogService;

    @Autowired
    private SysRecordLogService recordLogService;

    @Autowired
    private SysPermissionService permissionService;
    /**
     * 登录验证
     *
     * @param username 用户名
     * @param password 密码
     * @param code 验证码
     * @param uuid 唯一标识
     * @return 结果
     */
    /*public Map<String, Object> login(String username, String password, String code, String uuid, String tenantCode, String userType)
    {
        // 验证码校验
        validateCaptcha(username, code, uuid);
        // 登录前置校验
        loginPreCheck(username, password,tenantCode,userType);
        // 用户验证
       *//* Authentication authentication = null;
        try
        {
            TenantUsernamePasswordAuthenticationToken authenticationToken = new TenantUsernamePasswordAuthenticationToken(username, password,tenantCode);
            AuthenticationContextHolder.setContext(authenticationToken);
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager.authenticate(authenticationToken);
        }
        catch (Exception e)
        {
            if (e instanceof BadCredentialsException)
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            }
            else
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
                throw new ServiceException(e.getMessage());
            }
        }
        finally
        {
            AuthenticationContextHolder.clearContext();
        }*//*
        //TODO 暂时注释
        LoginUser userResult = null;
        if(SysContants.MANAGEDEPTFLAG.equals(userType)){
            //userResult = remoteManageService.getUserInfo(username,SecurityConstants.INNER);
        }else{
            //检查该租户是否被停用
            *//*R<String> stateInfo = userService.getStateInfo(tenantCode,SecurityConstants.INNER);
            String data = stateInfo.getData();
            if("1".equals(data)){
                throw new ServiceException("该租户未启用");
            }*//*
            userResult = userService.getUserInfo(username, tenantCode);
        }
        // 查询用户信息
        //R<LoginUser> userResult = remoteUserService.getUserInfo(username, SecurityConstants.INNER);

        if (StringUtils.isNull(userResult) || StringUtils.isNull(userResult))
        {
            sysRecordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "登录用户不存在",tenantCode);
            throw new ServiceException("登录用户：" + username + " 不存在");
        }


        LoginUser userInfo = userResult;
        SysUser user = userResult.getUser();
        if (UserStatus.DELETED.getCode().equals(user.getDelFlag()))
        {
            sysRecordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "对不起，您的账号已被删除",tenantCode);
            throw new ServiceException("对不起，您的账号：" + username + " 已被删除");
        }
        if (UserStatus.DISABLE.getCode().equals(user.getStatus()))
        {
            sysRecordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "用户已停用，请联系管理员",tenantCode);
            throw new ServiceException("对不起，您的账号：" + username + " 已停用");
        }
        if (!SysContants.MANAGEDEPTFLAG.equals(userType)&&(user.getRoles()==null||user.getRoles().size()==0))
        {
            sysRecordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "用户未分配角色，请联系管理员",tenantCode);
            throw new ServiceException("对不起，您的账号：" + username + " 未分配角色，请联系管理员");
        }
        if (!TokenParamUtil.isSoloTenant())
        {
            // 如果用户不允许多终端同时登录，清除缓存信息
            String userIdKey = Constants.LOGIN_USERID_KEY + userInfo.getUser().getUserId();
            String userKey = redisCache.getCacheObject(userIdKey);
            if (StringUtils.isNotEmpty(userKey))
            {
                redisCache.deleteObject(userIdKey);
                redisCache.deleteObject(userKey);
            }
        }
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        recordLoginInfo(userInfo.getUserId());
        sysPasswordService.validate(user, password,userType,tenantCode);
        // 生成token
        return tokenService.createToken(userInfo,userType);
    }*/

    public Map<String, Object> login(String username, String password, String code, String uuid, String tenantCode, String userType)
    {
        // 验证码校验
        validateCaptcha(username, code, uuid);
        // 登录前置校验
        loginPreCheck(username, password,tenantCode,userType);
        // 用户验证
        Authentication authentication = null;
        try
        {
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(tenantCode+"&&&"+username, password);
            AuthenticationContextHolder.setContext(authenticationToken);
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager.authenticate(authenticationToken);
        }
        catch (Exception e)
        {
            if (e instanceof BadCredentialsException)
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            }
            else
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
                throw new ServiceException(e.getMessage());
            }
        }
        finally
        {
            AuthenticationContextHolder.clearContext();
        }
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        recordLoginInfo(loginUser.getUserId());
        recordLogService.recordLogininfor(username, Constants.LOGIN_SUCCESS, "登录成功",tenantCode);
        // 生成token
        return tokenService.createToken(loginUser,userType);
    }


    public Map<String, Object> loginhta(Long userId)
    {
        SysUser sysUser = userService.selectUserById(userId);
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(sysUser);
        LoginUser loginUser =  new LoginUser(sysUser.getUserId(), sysUser.getDeptId(), sysUser, permissionService.getMenuPermission(sysUser), roles);
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(sysUser.getUserName(), Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        recordLoginInfo(sysUser.getUserId());
        recordLogService.recordLogininfor(sysUser.getUserName(), Constants.LOGIN_SUCCESS, "登录成功",sysUser.getTenantCode());
        // 生成token
        return tokenService.createToken(loginUser,"tenant");
    }

    public Map<String, Object> loginnf(String loginBody)
    {
        SysUser sysUser = userService.selectUserByRemark(loginBody);
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(sysUser);
        LoginUser loginUser =  new LoginUser(sysUser.getUserId(), sysUser.getDeptId(), sysUser, permissionService.getMenuPermission(sysUser), roles);
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(sysUser.getUserName(), Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        recordLoginInfo(sysUser.getUserId());
        recordLogService.recordLogininfor(sysUser.getUserName(), Constants.LOGIN_SUCCESS, "登录成功",sysUser.getTenantCode());
        // 生成token
        return tokenService.createToken(loginUser,"tenant");
    }


    /**
     * 校验验证码
     *
     * @param username 用户名
     * @param code 验证码
     * @param uuid 唯一标识
     * @return 结果
     */
    public void validateCaptcha(String username, String code, String uuid)
    {
        boolean captchaEnabled = YuanQiaoConfig.isCaptchaEnable();
        if (captchaEnabled)
        {
            String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + StringUtils.nvl(uuid, "");
            String captcha = redisCache.getCacheObject(verifyKey);
            redisCache.deleteObject(verifyKey);
            if (captcha == null)
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire")));
                throw new CaptchaExpireException();
            }
            if (!code.equalsIgnoreCase(captcha))
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error")));
                throw new CaptchaException();
            }
        }
    }

    /**
     * 登录前置校验
     * @param username 用户名
     * @param password 用户密码
     */
    public void loginPreCheck(String username, String password,String tenantCode, String userType)
    {
        // 用户名或密码为空 错误
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password))
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("not.null")));
            throw new UserNotExistsException();
        }
        // 密码如果不在指定范围内 错误
        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH)
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
            throw new UserPasswordNotMatchException();
        }
        // 用户名不在指定范围内 错误
        if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH)
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
            throw new UserPasswordNotMatchException();
        }
        // IP黑名单校验
        String blackStr = Convert.toStr(redisCache.getCacheObject("sys.login.blackIPList"));
        if (IpUtils.isMatchedIp(blackStr, IpUtils.getIpAddr()))
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("login.blocked")));
            throw new BlackListException();
        }
    }

    /**
     * 记录登录信息
     *
     * @param userId 用户ID
     */
    public void recordLoginInfo(Long userId)
    {
        SysUser sysUser = new SysUser();
        sysUser.setUserId(userId);
        sysUser.setLoginIp(IpUtils.getIpAddr());
        sysUser.setLoginDate(DateUtils.getNowDate());
        userService.updateUserProfile(sysUser);
    }
}
